package org.feng.resource.impl;

import com.aliyun.oss.OSSClientBuilder;
import org.feng.resource.ResourceUpload;
import org.feng.entity.Resource;
import org.feng.utils.UUIDUtil;

import java.io.InputStream;

/**
 * @author 冯帅
 * @des TODO
 * @date 2021/11/30 15:50
 * @email 15612509687@163.com
 */
public class OSS implements ResourceUpload {

    private final Resource resource;
    private final com.aliyun.oss.OSS ossClient;

    public OSS(Resource resource) {
        this.resource = resource;
        this.ossClient = new OSSClientBuilder().build(resource.getEndpoint(), resource.getKey(), resource.getSecret());
    }

    @Override
    public void createBucket(String name) {
        if (!ossClient.doesBucketExist(name)) {
            ossClient.createBucket(name);
        }
    }

    @Override
    public void deleteBucket(String name) {
        ossClient.deleteBucket(name);
    }

    @Override
    public String putFile(InputStream stream, String fileName, Boolean override) {
        if (override) {
            ossClient.putObject(resource.getBucket(), fileName, stream);
        } else {
            String suffix = fileName.substring(fileName.lastIndexOf("."));
            fileName = UUIDUtil.getUUID() + suffix;
            ossClient.putObject(resource.getBucket(), fileName, stream);
        }
        return getLink(fileName);

    }


    private String getLink(String fileName) {
        String url = "";
        if (this.resource.getEndpoint().contains("https://")) {
            url = this.resource.getEndpoint().replace("https://", "https://" + this.resource.getBucket() + ".");
        }
        if (this.resource.getEndpoint().contains("http://")) {
            url = this.resource.getEndpoint().replace("http://", "http://" + this.resource.getBucket() + ".");
        }
        return url + "/" + fileName;
    }
}
